<template>
  <view class="audit-page">
    <view class="audit-page-content">
      <view class="avatar-container">
        <u-avatar
          shape="square"
          :src="professorInfo.avatarUrl"
        ></u-avatar>
        <view class="avatar-content">
          <text>{{ professorInfo.name }}</text>
          <br />
          <text class="status-text">{{ statusText }}</text>
        </view>
      </view>
      <view class="label-value">
        <text class="label">申请人姓名：</text>
        <text class="value">{{ appointmentData.userName }}</text>
      </view>
      <view class="label-value">
        <text class="label">身份证号码：</text>
        <text class="value">{{ appointmentData.userIdCard }}</text>
      </view>
      <view class="label-value">
        <text class="label">联系方式：</text>
        <text class="value">{{ appointmentData.userPhone }}</text>
      </view>
      <view class="label-value">
        <text class="label">单位：</text>
        <text class="value">{{ appointmentData.userCompany }}</text>
      </view>
      <view class="label-value">
        <text class="label">预约专家：</text>
        <text class="value">{{ appointmentData.professorName }}</text>
      </view>
      <view class="label-value">
        <text class="label">预约时间：</text>
        <text class="value">{{ appointmentData.appointmentTime }}</text>
      </view>
      <view class="label-value">
        <text class="label">到访事项：</text>
        <text class="value">{{ appointmentData.appointmentContent }}</text>
      </view>
      <view class="label-value">
        <text class="label">审核情况</text>
      </view>
      <view class="log-list">
        <view
          class="log-item"
          v-for="(log, index) in logList"
          :key="index"
        >
          <view>
            <u-icon
              :name="getLogStatusIcon(log.auditingStatus)"
              :color="getLogStatusColor(log.auditingStatus)"
              size="25"
            ></u-icon>
          </view>
          <view class="log-content">
            <text class="log-status">{{
              getLogStatusText(log.auditingStatus)
            }}</text>
            <text class="log-time">{{ log.createTime }}</text>
          </view>
        </view>
      </view>
    </view>
    <view
      class="button-group"
      v-if="needAudit"
    >
      <u-button
        type="primary"
        @click="showConfirm('agree')"
      >
        同意
      </u-button>
      <u-button
        type="error"
        plain
        @click="showConfirm('reject')"
      >
        拒绝
      </u-button>
    </view>
  </view>
</template>

<script>
  import { appointment } from "@/api";
  import { ERROR_TYPE } from "@/common/constants";
  import {
    getStatusText,
    getStatusColor,
    showMessage,
    showLoading,
    hideLoading,
  } from "@/common/utils";
  import _ from "lodash";

  export default {
    data() {
      return {
        /**
         * 预约 ID
         * @property {String} id 预约 ID
         */
        id: "",
        /**
         * 预约详情数据
         * @property {Object} appointmentData 预约详情数据
         * @property {String} appointmentData.userName 申请人姓名
         * @property {String} appointmentData.userIdCard 身份证号
         * @property {String} appointmentData.userPhone 联系方式
         * @property {String} appointmentData.userCompany 工作单位
         * @property {String} appointmentData.professorName 预约专家
         * @property {String} appointmentData.appointmentTime 预约时间
         * @property {String} appointmentData.appointmentContent 到访事项
         * @property {String} appointmentData.createTime 创建时间
         */
        appointmentData: {},
        /**
         * 日志列表
         * @property {Array} logList 日志列表
         * @property {Number} logList.auditingStatus 审核状态
         * @property {String} logList.createTime 创建时间
         */
        logList: [],
        /**
         * 专家信息
         * @property {Object} professorInfo 专家信息
         * @property {String} professorInfo.id 专家ID
         * @property {String} professorInfo.name 专家姓名
         * @property {String} professorInfo.avatarUrl 专家头像
         */
        professorInfo: {},
      };
    },

    /**
     * 页面加载时调用
     */
    onLoad() {
      this.id = this.$route.query.id;
      this.initializeData();
    },
    async onPullDownRefresh() {
      await this.initializeData();
      uni.stopPullDownRefresh();
    },
    computed: {
      /**
       * 最后审核状态
       */
      lastAuditingStatus() {
        return _.last(this.logList)?.auditingStatus;
      },
      /**
       * 状态文本
       */
      statusText() {
        return getStatusText(this.lastAuditingStatus);
      },
      /**
       * 是否需要审核
       */
      needAudit() {
        return this.lastAuditingStatus === 0;
      },
    },
    methods: {
     /**
		 * 初始化数据
		 */
      async initializeData() {
        try {
          this.professorInfo = this.$store.state.professor.professorInfo;
          await this.fetchAppointmentDetail();
        } catch (err) {
          showMessage("初始化数据失败", false);
        }
      },

      /**
       * 获取预约详情
       */
      async fetchAppointmentDetail() {
        showLoading("获取预约详情...");
        try {
          const res = await appointment.getAppointmentDetail({
            id: this.id,
          });
          this.appointmentData = res.data.appointment;
          this.logList = res.data.logList;
          this.showButtons = true;
        } catch (error) {
          if (error.type === ERROR_TYPE.NETWORK) {
            return;
          }
          showMessage(error.msg || "获取预约详情失败", false);
        } finally {
          hideLoading();
        }
      },

      /**
       * 更新预约审核数据
       * @param {Number} newStatus 新状态
       */
      async updateAppointment(newStatus) {
        try {
          const res = await appointment.updateAppointment({
            id: this.id,
            status: newStatus,
          });
          this.logList = res.data.logList;
        } catch (error) {
          if (error.type === ERROR_TYPE.NETWORK) {
            return;
          }
          showMessage(error.msg || "获取更新审核数据失败", false);
        }
      },

      /**
       * 显示确认操作对话框
       * @param {String} action 操作类型，'agree' 或 'reject'
       */
      async showConfirm(action) {
        uni.showModal({
          title: "确认操作",
          content:
            action === "agree"
              ? "确定要同意该预约吗？"
              : "确定要拒绝该预约吗？",
          showCancel: true,
          success: async (res) => {
            if (res.confirm) {
              showLoading("正在更新审核数据...");
              const newStatus = action === "agree" ? 1 : 2;
              await this.updateAppointment(newStatus);
              hideLoading();
            }
          },
        });
      },

      /**
       * 根据状态值返回对应的文本
       * @param {Number} status 状态值
       * @returns {String} 状态文本
       */
      getLogStatusText(status) {
        // 根据状态值返回对应的文本
        switch (status) {
          case 1:
            return "审核通过";
          case 2:
            return "审核拒绝";
          default:
            return "申请";
        }
      },

      /**
       * 根据状态值返回对应的图标
       */
      getLogStatusIcon(status) {
        switch (status) {
          case 1:
            return "checkmark-circle";
          case 2:
            return "close-circle";
          default:
            return "more-circle";
        }
      },

      /**
       * 根据状态值返回对应的图标颜色
       */
      getLogStatusColor(status) {
        return getStatusColor(status);
      },
    },
  };
</script>

<style lang="scss" scoped>
  .audit-page {
    display: flex;
    flex-direction: column;
    margin: var(--margin-base);
    gap: var(--margin-small);

    .audit-page-content {
      display: flex;
      flex-direction: column;
      gap: var(--margin-small);

      .avatar-container {
        display: flex;
        flex-direction: row;

        .avatar-content {
          margin-left: var(--margin-base);

          .status-text {
            font-size: var(--font-size-small);
          }
        }
      }

      .label-value {
        display: flex;
        flex-direction: row;
        justify-content: space-between;

        .label {
          white-space: nowrap;
          font-weight: bold;
          flex-basis: 28%;
        }

        .value {
          flex-basis: 72%;
          text-align: left;
          justify-content: flex-start;
        }
      }

      .log-list {
        display: flex;
        flex-direction: column;
        gap: var(--margin-small);

        .log-item {
          display: flex;
          flex-direction: row;

          .log-content {
            display: flex;
            flex-direction: column;
            margin-left: var(--margin-small);

            .log-status {
              font-size: var(--font-size-small);
              color: #333;
            }

            .log-time {
              font-size: var(--font-size-small);
              color: #666;
            }
          }
        }
      }
    }

    .button-group {
      display: flex;
      gap: var(--margin-small);
    }
  }
</style>
